<?php
require_once 'conexao.php';

$login = @$_SESSION['login'];
$rg = @$_POST['rg'];
$cracha = @$_POST['cracha'];
$permissao = @strtoupper(strtr($_POST['permissao'] ,"áéíóúâêôãõàèìòùç","ÁÉÍÓÚÂÊÔÃÕÀÈÌÒÙÇ"));;
$nome = @strtoupper(strtr($_POST['nome'] ,"áéíóúâêôãõàèìòùç","ÁÉÍÓÚÂÊÔÃÕÀÈÌÒÙÇ"));
$sobrenome = @strtoupper(strtr($_POST['sobrenome'] ,"áéíóúâêôãõàèìòùç","ÁÉÍÓÚÂÊÔÃÕÀÈÌÒÙÇ"));
$empresa = @strtoupper(strtr($_POST['empresa'] ,"áéíóúâêôãõàèìòùç","ÁÉÍÓÚÂÊÔÃÕÀÈÌÒÙÇ"));
$setor = @$_POST['setor'];
$obs = @strtoupper(strtr($_POST['obs'] ,"áéíóúâêôãõàèìòùç","ÁÉÍÓÚÂÊÔÃÕÀÈÌÒÙÇ"));
$foto = './fotos/' . $rg . '.jpg';


if ((empty($rg) or empty($cracha))) {
    echo "<script type='text/javascript'>
     alert('Todos campos devem ser preenchidos corretamente.'); document.location.href='\index.php?pagina=visitantes'
     </script> ";
} else {

    $query = "SELECT dt_saida, id FROM visitante where id = (SELECT MAX(id) from visitante WHERE rg = " . $rg . ")";
    $result = mysql_query($query);
    echo mysql_error();

    $row = mysql_fetch_array($result, MYSQL_ASSOC);

    if ($row['dt_saida'] == '0000-00-00') {
        $query = "UPDATE visitante SET dt_saida = NOW(), hr_saida = NOW(), port_saida = '" . $login . "' WHERE id=" . $row['id'];
        mysql_query($query);
        echo mysql_error();
    }
    else {
        $query = "INSERT INTO visitante (dt_entrada, hr_entrada, rg, permissao, cracha, port_ent, setor, obs) VALUES (NOW(), NOW()," . $rg . ", '" . $permissao . "', " . $cracha . ", '" . $login . "', '" . $setor . "', '" . $obs . "')";
        mysql_query($query);
        echo mysql_error();
    }

    echo "<script type='text/javascript'>
     alert('Cadastrado com sucesso !'); document.location.href='index.php?pagina=visitantes'
  </script> ";
}
?>
